package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.config.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.LoginInfoUtil;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.pojo.domain.Employee;
import cn.itsource.org.pojo.dto.LoginDto;
import cn.itsource.org.pojo.vo.LoginInfo;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee, EmployeeQuery> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public AjaxResult loginSystem(LoginDto pageEmployee) {
        //1.拿到账号，账号拿去匹配  select * from t_employee where username = #{username} or email = #{username} or phone = #{username}
        Employee dbEmployee = employeeMapper.findByUsernameOrEmailOrPhone(pageEmployee.getUsername());

        //2.如果拿到了，匹配面
        /*if (dbEmployee == null){
            throw new BusinessException("账号名与密码不匹配，请重新输入111111");
        }*/
        Optional.ofNullable(dbEmployee).orElseThrow(() ->new BusinessException("账号名与密码不匹配，请重新输入"));
        //流程 页面传递过来的明文，进行加盐（数据库的老盐）加密   和数据的password进行对比
        String pwd = MD5.create().setSalt(dbEmployee.getSalt().getBytes()).digestHex(pageEmployee.getPassword());
        if (!StringUtils.equals(pwd, dbEmployee.getPassword())){
            throw new BusinessException("账号名与密码不匹配，请重新输入222222");
        }
        //3.如果比对通过，生成token令牌（uuid），用户信息（需要兼容employee和user的）存到redis
        String token = IdUtil.fastSimpleUUID();
        //拷贝对象的相同字段，底层通过get  set方法操作的
        LoginInfo loginInfo = BeanUtil.copyProperties(dbEmployee, LoginInfo.class);
        loginInfo.setToken(token);
        loginInfo.setShopId(dbEmployee.getShopId());
        //存到redis
        redisService.setStringKeyAndValue(token,loginInfo,30);

        //4.返回用户信息 和 token令牌
        return AjaxResult.createSuccess(loginInfo);
    }

    @Override
    public List<Employee> findByShopId() {

        //1.从LoginInfoUtil里面拿shopId
        Long shopId = LoginInfoUtil.getShopId();

        //2.调用语句
        return employeeMapper.findByShopId(shopId);
    }


    @Override
    public List<Employee> findManager() {
        return employeeMapper.findManager();
    }


}